from django.db import models
import django_filters
import django_filters as filters

from accounts.models import (
    StorageMenu,
    VideoFileAddres,
    Department,
    Consumer, config,
)


class DepartmentFilter(filters.rest_framework.FilterSet):
    class Meta:
        model = Department
        fields = "__all__"


class configFilter(django_filters.FilterSet):
    # 手动定义 logo_file 的过滤器
    logo_file = django_filters.CharFilter(field_name='logo_file', lookup_expr='exact')

    class Meta:
        model = config
        fields = {
            'name': ['exact', 'icontains'],
            'logo_file': ['exact'],  # 或者你可以在这里添加其他查找表达式
        }


class UserFilter(filters.rest_framework.FilterSet):
    mobile = filters.CharFilter(field_name="mobile", lookup_expr="icontains")

    class Meta:
        model = Consumer
        fields = "__all__"


class MenuFilter(filters.rest_framework.FilterSet):
    belong_sys = filters.CharFilter(
        method="getBelongSystem", label="系统类别", lookup_expr="icontains"
    )
    user_id = filters.CharFilter(
        method="getUserMenu", label="根据用户id获取菜单", lookup_expr="icontains"
    )

    def getBelongSystem(self, queryset, name, value):
        if value == "dingwei":
            return queryset.filter(belong_sys=value)
        else:
            # belong_sys 传值进来 zuxun 查找非组训的全部数据，反之亦然
            return queryset.filter(belong_sys__in=[value, "all"])

    def getUserMenu(self, queryset, name, value):
        userObj = Consumer.objects.get(pk=value)
        queryset = queryset.filter(
            belong_role=userObj.belong_role, belong_department=userObj.belong_department
        )
        return queryset

    class Meta:
        model = StorageMenu
        fields = "__all__"


class VideoUrlFilter(filters.FilterSet):
    class Meta:
        model = VideoFileAddres
        fields = "__all__"
        filter_overrides = {
            models.FileField: {
                "filter_class": django_filters.CharFilter,
                "extra": lambda f: {"lookup_expr": "video"},
            }
        }